﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace Super.Infrastructure
{
   public static class QueryExtention
    {
        /// <summary>
        /// 获取分页集合。
        /// </summary>
        /// <typeparam name="TEntity">实体类型。</typeparam>
        /// <param name="source">实体数据集合。</param>
        /// <param name="pageIndex">当前页码。</param>s
        /// <param name="pageSize">分页大小。</param>
        /// <returns>返回分页实体。</returns> 
        public static PagedEntities<TEntity> Page<TEntity>(this IEnumerable<TEntity> source, int pageIndex, int pageSize)
            where TEntity : class , new()
        {
            Debug.Assert(source != null, "source != null");
            return new PagedEntities<TEntity>(pageIndex, pageSize, source.Skip((pageIndex - 1) * pageSize).Take(pageSize),source.Count());
        }

       /// <summary>获取分页集合。
        /// </summary>
        /// <typeparam name="TEntity">实体类型。</typeparam>
        /// <param name="source">实体数据集合。</param>
        /// <param name="pageNumber">当前页码。</param>s
        /// <param name="pageSize">分页大小。</param>
        /// <returns>返回分页实体。</returns>
        public static PagedEntities<TEntity> Page<TEntity>(this IQueryable<TEntity> source, int pageNumber, int pageSize)
        {
            //IEnumerable 是枚举接口  IQueryable 是针对数据源的查询接口 两者.Count() 方法实现逻辑不同.
            //前者是查询出完整的实体,然后计算数量..后者是直接生成查询数量所需的查询语句,直接返回数量.
            //Entity To Sql Skip Take 之前要求有 OrderBy. 
            if (pageNumber > 0)
            {
                IQueryable<TEntity> query;
                var ss = source.ToString().ToUpper();
                if (ss.IndexOf("ORDER BY", System.StringComparison.Ordinal) > 0 || ss.IndexOf("ORDERBY", System.StringComparison.Ordinal) > 0)
                {
                    query = source.Skip((pageNumber - 1) * pageSize).Take(pageSize);
                }
                else
                {
                    query = source.OrderBy(j => 1).Skip((pageNumber - 1) * pageSize).Take(pageSize);
                }
                return new PagedEntities<TEntity>(pageNumber, pageSize, query,source.Count()) { SourceQueryable = source };
            }
            else
            {
                throw new Exception("pageNumber 必须 > 0");
            }
        }
    }
}
